package com.example.pt.controller;

import com.example.pt.repository.UserRepository;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.dampcake.bencode.Bencode;
import com.dampcake.bencode.Type;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/tracker")
public class TrackerController {
    private final Bencode bencode = new Bencode(StandardCharsets.UTF_8);


    @GetMapping(value = "/announce", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<byte[]> announce(
            @RequestParam(name = "info_hash") String infoHash,
            @RequestParam(name = "peer_id") String peerId,
            @RequestParam(name = "port") int port,
            @RequestParam(defaultValue = "0") long uploaded,
            @RequestParam(defaultValue = "0") long downloaded,
            @RequestParam(defaultValue = "0") long left,
            @RequestParam(required = false) String event,
            HttpServletRequest request) throws IOException {

        // 1. 参数验证
        if (infoHash.length() != 20 || peerId.length() != 20) {
            return errorResponse("Invalid info_hash or peer_id (must be 20 bytes)");
        }

        // 2. 构造响应数据
        Map<String, Object> response = new HashMap<>();
        response.put("interval", 1800); // 下次announce间隔（秒）
        response.put("complete", 0);    // 当前做种者数量
        response.put("incomplete", 0);  // 当前下载者数量
        response.put("peers", List.of()); // 返回空peer列表（测试阶段）

        // 3. 记录请求日志（调试用）
        System.out.println("[Tracker] Announce received: " +
                "info_hash=" + infoHash + ", " +
                "peer_id=" + peerId + ", " +
                "port=" + port);

        return ResponseEntity.ok(bencode.encode(response));
    }

    private ResponseEntity<byte[]> errorResponse(String message) {
        return ResponseEntity.badRequest()
                .body(bencode.encode(Map.of("failure reason", message)));
    }
    private Map<String, String> extractParameters(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Enumeration<String> paramNames = request.getParameterNames();

        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            params.put(paramName, request.getParameter(paramName));
        }
        return params;
    }

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.split(",")[0]; // 处理多级代理情况
    }
}